from collections import defaultdict
import sys,re

def mycostat(samfile,outfile):
    allread = defaultdict(set)
    uniqread_num = defaultdict(int)
    multiread_num = defaultdict(int)
    allread_num = defaultdict(int)
    with open(outfile,'w') as out:
        for i in sys.stdin:
            e =  i.strip().split('\t')
            #if list(set('*SHIDM') & set(e[5]))[0] == 'M' and e[11] == 'NM:i:0':
            if re.search('^\d+M$',e[5]) and e[11] == 'NM:i:0':
                myco_name = e[2].split('|')[0]
                uniqread_num[myco_name] = 0
                multiread_num[myco_name] = 0
                allread_num[myco_name] = 0
                allread[e[0]].add(myco_name)

        for k,v in allread.items():
            if len(list(v)) == 1:
                uniqread_num[list(v)[0]] += 1
                allread_num[list(v)[0]] += 1
            else:
                for i in list(v):
                    multiread_num[i] += 1
                    allread_num[i] += 1

        out.write('species\tuniq\tmulti\tall\n')
        for k,v in allread_num.items():
            out.write(k+'\t'+str(uniqread_num[k])+'\t'+str(multiread_num[k])+'\t'+str(allread_num[k])+'\n')

if __name__ == "__main__":
    sam_file = sys.argv[1]
    out_file = sys.argv[2]
    mycostat(sam_file,out_file)                


